package com.leetcode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * 310. 最小高度树
 * 拓扑排序
 *
 * @author fy
 * @date 2022/4/7 9:45
 */
public class Solution301_2 {

    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        List<Integer> res = new ArrayList<>();
        if (n <= 0) {
            return res;
        }
        if (n == 1) {
            res.add(0);
            return res;
        }
        if (n == 2) {
            res.add(0);
            res.add(1);
            return res;
        }

        // 初始化邻接表
        List<Integer>[] adj = new List[n];
        for (int i = 0; i < n; i++) {
            adj[i] = new ArrayList<>();
        }

        // 记录下标对应节点的度
        int[] degree = new int[n];
        for (int[] edge : edges) {
            adj[edge[0]].add(edge[1]);
            adj[edge[1]].add(edge[0]);

            degree[edge[0]]++;
            degree[edge[1]]++;
        }

        Queue<Integer> queue = new ArrayDeque<>();
        for (int i = 0; i < n; i++) {
            if (degree[i] == 1) {
                queue.offer(i);
            }
        }

        int remainNodes = n;
        while (remainNodes > 2) {
            int sz = queue.size();
            remainNodes -= sz;
            for (int i = 0; i < sz; i++) {
                int node = queue.poll();
                for (Integer edge : adj[node]) {
                    degree[edge]--;
                    if (degree[edge] == 1) {
                        queue.offer(edge);
                    }
                }
            }
        }

        // 将最终剩下的一个或两个节点返回
        while (!queue.isEmpty()) {
            res.add(queue.poll());
        }

        return res;
    }

}
